﻿namespace TrackSystem.IO.Utils
{
    /// <summary>
    /// 滤波器变量实用类
    /// </summary>
    public class FilterHelper
    {
        /// <summary>
        /// 滤波器输入值
        /// </summary>
        public double Value { get; private set; }

        private const int QueueLen = 10;
        private double Sum;
        private double[] QueueBuf;
        private int ptrHead;
        private int CurLen;

        /// <summary>
        /// 构造函数
        /// </summary>
        public FilterHelper()
        {
            Value = 0.0d;
            Sum = 0.0;
            QueueBuf = new double[QueueLen];
            for (int i = 0; i < QueueLen; i++)
                QueueBuf[i] = 0;
            ptrHead = 0;
            CurLen = 0;
        }

        /// <summary>
        /// 数据进入队列，并返回当前数据的10次平均值
        /// </summary>
        /// <param name="val"></param>
        /// <returns></returns>
        public double Enqueue(double val)
        {
            Sum += val;
            Sum -= QueueBuf[ptrHead];

            QueueBuf[ptrHead] = val;
            ptrHead = (ptrHead + 1) % QueueLen;

            CurLen++;
            if (CurLen > QueueLen)
                CurLen = QueueLen;

            Value = Sum / QueueLen;
            return Value;
        }
    }
}
